package com.lvbaoins.creditapp.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.lvbaoins.creditapp.core.exception.RequestEmptyException;
import com.lvbaoins.creditapp.core.exception.ServiceException;
import com.lvbaoins.creditapp.core.exception.enums.ErrorExceptionEnum;
import com.lvbaoins.creditapp.core.reqres.Error;
import com.lvbaoins.creditapp.core.reqres.ResponseData;
import com.lvbaoins.creditapp.model.InsUser;
import com.lvbaoins.creditapp.service.InsUserService;
import com.lvbaoins.creditapp.task.MailTask;
import com.lvbaoins.creditapp.task.ScheduledThreadPoolExecutorUtil;
import com.lvbaoins.creditapp.util.PasswordUtil;
import com.lvbaoins.creditapp.util.UserTokenManager;
import com.lvbaoins.creditapp.util.ValidateUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@ApiResponses({@ApiResponse(code = 10001, message = "失败", response = Error.class)})
@RestController
@RequestMapping("/wx/auth")
@Api(value = "微信登陆相关", tags = "登陆相关")
@Slf4j
public class WxAuthController extends BaseController {

    @Autowired
    private WxMaService wxService;

    @Autowired
    private InsUserService insUserService;

    @Value("${spring.mail.fromAddr}")
    private String[] to;


    @ApiOperation(value = "微信登陆", notes = "成功时返回token和用户信息，失败时返回sessionKey和openId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "code", required = true, dataType = "string"),
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "{'openId':'XXXXX','sessionKey':'xxxxxxxxxxx'}")
    })
    @PostMapping(value = "login_by_weixin", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ResponseData loginByWeixin(@RequestParam String code) {

        if (code == null) {
            return ResponseData.error("参数错误,请检查是否");
        }
        String sessionKey = null;
        String openId = null;
        try {
            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
        } catch (Exception e) {
            log.error("[微信登陆]-访问微信服务器错误：", e);
        }
        if (sessionKey == null || openId == null) {
            return ResponseData.error("请求微信服务器错误");
        }

        InsUser insUser = insUserService.getUserByOpenId(openId);
        Map<Object, Object> result = new HashMap<Object, Object>();
        if (insUser == null) {
            log.info("[微信登陆]-当前客户不存在需要进行登陆或注册,openId:{}", openId);
            result.put("openId", openId);
            return ResponseData.error(10001,"当前客户不存在", openId);
        } else {
            log.info("[微信登陆]-当前客户存在生成token令牌，当前客户:{}", insUser.getName());
            String token = UserTokenManager.generateToken(insUser.getId());
            result.put("token", token);
            result.put("userInfo", insUser);
            return ResponseData.success(result);
        }
    }

    /**
     * 点击登录执行的动作
     *
     * @author gjb
     * @Date
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData login(@RequestParam String openId, @RequestParam String username, @RequestParam String password) {


        if (ValidateUtil.isOneEmpty(openId, username, password)) {
            throw new RequestEmptyException("账号或密码为空！");
        }
        InsUser insUser = insUserService.getUserByAccount("C" + username);
        if (insUser == null) {
            throw new ServiceException(ErrorExceptionEnum.LOGIN_ERROR);
        }
        //类型为1:渠道
        if (insUser.getType() != 1) {
            throw new ServiceException(ErrorExceptionEnum.LOGIN_NO_PERMISSION);
        }
        //验证账号密码是否正确
        String requestMd5 = PasswordUtil.createPassword(password, insUser.getUserCode());
        String dbMd5 = insUser.getPassword();
        if (dbMd5 == null || !dbMd5.equalsIgnoreCase(requestMd5)) {
            throw new ServiceException(ErrorExceptionEnum.USERNAME_PWD_ERROR);
        }
        InsUser insUser1 = new InsUser();
        insUser1.setId(insUser.getId());
        insUser1.setOpenId(openId);
        this.insUserService.updateById(insUser1);
        String token = UserTokenManager.generateToken(insUser.getId());
        Map<Object, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("name", insUser.getName());
        return ResponseData.success(result);
    }



    @ApiOperation(value = "注册", notes = "成功code：10000，返回成功")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "string"),
            @ApiImplicitParam(name = "name", value = "民称", required = true, dataType = "string"),
    })
    @PostMapping(value = "/register", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ResponseData register(String mobile, String name) {

        if (ValidateUtil.isOneEmpty(mobile, name)) {
            return ResponseData.error("参数错误,请检查是否");
        }
        ScheduledThreadPoolExecutorUtil.getInstance().execute(MailTask.sendPolicyTask(to, name, mobile));
        return ResponseData.success();
    }


}
